package top100.backtrack;

import java.util.*;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/16 13:25
 * @description: 给你一个整数数组 nums ，其中可能包含重复元素，请你返回该数组所有可能的 子集（幂集）。
 * <p>
 * 解集 不能 包含重复的子集。返回的解集中，子集可以按 任意顺序 排列。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：nums = [1,2,2]
 * 输出：[[],[1],[1,2],[1,2,2],[2],[2,2]]
 * 示例 2：
 * <p>
 * 输入：nums = [0]
 * 输出：[[],[0]]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 1 <= nums.length <= 10
 * -10 <= nums[i] <= 10
 */
public class Solution90 {
    Set<String> set = new HashSet<>();

    public void backtrack(int[] nums, int start, LinkedList<Integer> path, List<List<Integer>> res) {
        if (start > nums.length) {
            return;
        }
        if (!set.contains(path.toString())) {
            set.add(path.toString());
            res.add(new ArrayList<>(path));
        }
        for (int i = start; i < nums.length; i++) {
            path.addLast(nums[i]);
            backtrack(nums, i + 1, path, res);
            path.removeLast();
        }
    }

    public void backtrack2(int[] nums, int start, LinkedList<Integer> path, List<List<Integer>> res, boolean[] used) {
        if (start > nums.length) {
            return;
        }

        res.add(new ArrayList<>(path));

        for (int i = start; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false){
                continue;
            }
            path.addLast(nums[i]);
            used[i] = true;
            backtrack2(nums, i + 1, path, res,used);
            used[i] = false;
            path.removeLast();
        }
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        backtrack(nums, 0, new LinkedList<>(), res);
        return res;
    }
    public List<List<Integer>> subsetsWithDup2(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        boolean used[] = new boolean[nums.length];
        backtrack2(nums, 0, new LinkedList<>(), res,used);
        return res;
    }

    public static void main(String[] args) {
        Solution90 solution = new Solution90();
        List<List<Integer>> res = solution.subsetsWithDup(new int[]{1, 2, 2});
        System.out.println(res);
        res = solution.subsetsWithDup2(new int[]{1, 2, 2});
        System.out.println(res);
    }

}
